package club.itstudio.itouc.controller.jw.stu

import club.itstudio.itouc.core.annotation.ElectiveConf
import club.itstudio.itouc.core.util.*
import club.itstudio.itouc.entity.ElectiveCourse
import club.itstudio.itouc.jw.ParamsBuilder
import club.itstudio.itouc.jw.Parser
import club.itstudio.itouc.jw.with
import club.itstudio.itouc.service.JwOps
import com.fasterxml.jackson.module.kotlin.readValue
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/jw/stu/course/elective")
class ElectiveCourse (val jwOps: JwOps,
                      val jw: ParamsBuilder,
                      val parser: Parser){

    val logger = logger()
    /**
     * 选课
     */
    @ElectiveConf
    @PostMapping("/save")
    fun save(@CookieValue token: String,
             @RequestBody ec: ElectiveCourse): Result<Any>{
        val session = jwOps.getValidJwSession(token)
        // 选课前确认
        var data = jw.confirmCanElective(session.userCode, ec.classCode) with session
        var result:Map<String, String> = mapper.readValue(data)
        if (result["status"] != "200") return ResultUtil.error("您无法选择这门课，请核实")
        // 选课
        val keyTime = parser.keyTimeParam(jw.keyTimeParam() with session)
        data = jw.saveCourse(session.userCode, ec, keyTime) with session
        result = mapper.readValue(data)
        return if(result["status"] != "200")  ResultUtil.error("操作失败")
        else  ResultUtil.success()
    }

    /**
     * 修改
     */
    @ElectiveConf
    @PostMapping("/modify")
    fun modify(@CookieValue token: String,
               @RequestBody ec: ElectiveCourse): Result<Any> {
        val session = jwOps.getValidJwSession(token)
        // 先删除
        var keyTime = parser.keyTimeParam(jw.keyTimeParam() with session)
        var data = jw.cancelCourse(session.userCode, ec.classNum, ec.classCode, keyTime) with session
        var result: Map<String, String> = mapper.readValue(data)
        if (result["status"] != "200") return ResultUtil.error("修改失败")
        // 重新选课
        keyTime = parser.keyTimeParam(jw.keyTimeParam() with session)
        data = jw.saveCourse(session.userCode, ec, keyTime) with session
        result = mapper.readValue(data)
        return if(result["status"] != "200")  ResultUtil.error("修改失败")
        else ResultUtil.success()
    }

    /**
     * 删除
     */
    @ElectiveConf
    @PostMapping("/delete")
    fun deleteCourse(@CookieValue token: String,
                     @RequestParam classNum: String,
                     @RequestParam classCode: String): Result<Any> {
        val session = jwOps.getValidJwSession(token)
        // 删除
        var keyTime = parser.keyTimeParam(jw.keyTimeParam() with session)
        val data = jw.cancelCourse(session.userCode, classNum, classCode, keyTime) with session
        val result: Map<String, String> = mapper.readValue(data)
        return if(result["status"] != "200") ResultUtil.error("修改失败")
        else ResultUtil.success()
    }
}